package com.example.demo.test;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;

public class demo8 {

    private static BlockingQueue blockingQueue1 = new ArrayBlockingQueue<>(100);

    private static AtomicBoolean isA1 = new AtomicBoolean(true);

    public static void main(String[] args) {
        demo8 demo8 = new demo8();
        for (int i = 0; i < 100; i++) {
            blockingQueue1.add(i);
        }
        Thread thread1 = new Thread(()->{
            try {
                demo8.consumer("c1");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Thread thread2 = new Thread(()->{
            try {
                demo8.consumer("c2");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        thread1.start();
        thread2.start();
        try{
            thread1.join();
            thread2.join();
        }catch (InterruptedException e) {
            e.printStackTrace();
        } finally {

        }
    }

    private synchronized void consumer(String name) throws InterruptedException {
        while (true){
            if ("c1".equals(name)){
                if (!isA1.get()){
                    wait();
                    continue;
                }
            }else{
                if (isA1.get()){
                    wait();
                    continue;
                }
            }
            System.out.println(name+":"+blockingQueue1.take());
            isA1 = new AtomicBoolean(!isA1.get());
            notifyAll();
        }
    }

    // 不用原子的Boolean也可以。
    // wait();
}
